package cn.dw.action;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;





import cn.dw.dao.ReaderDao;
import cn.dw.db.DBO;
import cn.dw.model.Reader;
import cn.dw.util.AddStudentUntil;

public class ReaderAction {

	public void update(){
		//		新增的数据
		List<Reader> addReader = new ArrayList<Reader>();
		//		修改的数据
		List<Reader> updateReader = new ArrayList<Reader>();

		//		图书馆的数据
		ReaderDao readerDao = new ReaderDao();
		DBO dbo = new DBO();

		//		通过图书馆的数据查找，数据是为修改数据和新增数据
		List<Reader> reader = readerDao.query();
		System.out.println(reader.size());  
		
		PreparedStatement preparedStatement2 = null;
		Connection con2=dbo.getCon();
		String sql2 = "select dzzh from dzxxb where xlh = ?";
		try {
			preparedStatement2=con2.prepareStatement(sql2);
		} catch (SQLException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		
		
		for (Reader reader2 : reader) {
			ResultSet rs = null;
			try {
				preparedStatement2.setString(1, reader2.getXlh());
				rs =preparedStatement2.executeQuery();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			
			//		查看这条数据是存在
//			ResultSet rs = dbo.getRs("select dzzh from dzxxb where xlh = "+reader2.getXlh().replaceAll(" +",""));
			
			//是否有数据
			try {
				if(rs.next() == false){
					addReader.add(reader2);
					//					NullPointerException
				}else{

					if(rs.getString(1).equals(reader2.getDzzh())){

					}else{
						System.out.println(rs.getString(1));
						//	修改到卡机数据 和内置数据库数据
						updateReader.add(reader2);
					}
				}
			} catch (NullPointerException e) {
				//如果没有查询到的话新增数据到卡机和 
				addReader.add(reader2);
				// TODO Auto-generated catch block
			}catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		System.out.println(updateReader.size());  
		System.out.println(addReader.size());  
		//		接着写
		AddStudentUntil a = new AddStudentUntil();
		try {
			for (Reader reader2 : addReader) {
				dbo.update("INSERT INTO dzxxb (xlh,dzzh) VALUES (?,?)",reader2.getXlh(),reader2.getDzzh());
				a.addStudent(reader2);
			}
		}catch (NullPointerException e) {
		}


		try {
			for (Reader reader2 : updateReader) {
				dbo.update("UPDATE dzxxb set dzzh = ? where xlh = ?",reader2.getDzzh(),reader2.getXlh());
				a.updateStudent(reader2);
			}
		}
		catch (NullPointerException e) {
		}

	}
}
